<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form-model
        layout="inline"
        ref="myForm"
        :model="form"
        :rules="validatorRules"
        :label-col="{ style: { width: '150px' } }"
      >
        <a-row :gutter="24">
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="代理商ID">
              <a-input allowClear disabled class="per100" placeholder="请输入" v-model="form.id" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="提现手续费（%）" prop="withdrawalFee">
              <a-input allowClear class="per100" placeholder="请输入" v-model="form.withdrawalFee" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="订单分成（%）" prop="orderSharding">
              <a-input allowClear class="per100" placeholder="请输入" v-model="form.orderSharding" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="手机号码" prop="phone">
              <a-input allowClear class="per100" placeholder="请输入" v-model="form.phone" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="密码明文" prop="passwordPlaintext">
              <a-input allowClear class="per100" placeholder="请输入" v-model="form.passwordPlaintext" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="姓名" prop="realname">
              <a-input allowClear placeholder="请输入" v-model="form.realname" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="性別" prop="sex">
              <j-dict-select-tag
                allowClear
                v-model="form.sex"
                placeholder="请选择"
                dictCode="sex"
                @input="
                  () => {
                    $refs.myForm.validateField('sex')
                  }
                "
              />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="昵称" prop="nickName">
              <a-input allowClear placeholder="请输入" v-model="form.nickName" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="联系电话">
              <a-input allowClear class="per100" placeholder="请输入" v-model="form.telephone" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="提现方式" prop="withdrawalMethod">
              <j-dict-select-tag
                allowClear
                v-model="form.withdrawalMethod"
                placeholder="请选择"
                dictCode="withdrawType"
                @input="
                  () => {
                    $refs.myForm.validateField('withdrawalMethod')
                  }
                "
              />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="身份证" prop="idCard">
              <a-input allowClear v-model="form.idCard" placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="微信实名">
              <a-input allowClear placeholder="请输入" v-model="form.wechatRealname" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="未提现金额（元）">
              <a-input allowClear disabled v-model="form.undrawnAmount" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="已提现金额（元）">
              <a-input allowClear disabled v-model="form.withdrawnAmount" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="储备资金（元）">
              <a-input allowClear v-model="form.reserveAmount" placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="储备金设置" prop="reserveSet">
              <a-input allowClear v-model="form.reserveSet" placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="QQ号码">
              <a-input allowClear placeholder="请输入" v-model="form.qqNum" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="EMAIL">
              <a-input allowClear placeholder="请输入" v-model="form.email" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="代理商类型" prop="agentType">
              <j-dict-select-tag
                allowClear
                disabled
                v-model="form.agentType"
                placeholder="请选择"
                dictCode="agentType"
              />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="24" :xl="16">
            <a-form-model-item label="代理区域" prop="agentArea" class="my-required">
              <a-row :gutter="5" :style="{ 'margin-bottom': 0, 'vertical-align': 'top' }">
                <a-col :span="6">
                  <a-select
                    placeholder="请选择省"
                    v-model="form.provinceCode"
                    @change="(e, data) => addressChange(e, 'cityOptions', 'province', data.key)"
                  >
                    <a-select-option v-for="item in provinceOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="6">
                  <a-select
                    placeholder="请选择市"
                    v-model="form.cityCode"
                    @change="(e, data) => addressChange(e, 'areaOptions', 'city', data.key)"
                  >
                    <a-select-option v-for="item in cityOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="6">
                  <a-select
                    placeholder="请选择区"
                    v-model="form.areaCode"
                    @change="(e, data) => addressChange(e, 'streetOptions', 'area', data.key)"
                  >
                    <a-select-option v-for="item in areaOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="6">
                  <a-select
                    placeholder="请选择街道"
                    v-model="form.streetCode"
                    @change="(e, data) => addressChange(e, '', 'street', data.key)"
                  >
                    <a-select-option v-for="item in streetOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="加盟日期" prop="joinData">
              <a-date-picker class="per100" v-model="form.joinData" valueFormat="YYYY-MM-DD" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="最后登录时间">
              <a-input disabled class="per100" v-model="form.lastLoginTime"></a-input>
              <!-- <a-date-picker disabled class="per100" v-model="form.createTime" valueFormat="YYYY-MM-DD" /> -->
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="提现人工审批" prop="withdrawalManualApproval">
              <j-dict-select-tag
                v-model="form.withdrawalManualApproval"
                @input="
                  () => {
                    $refs.myForm.validateField('withdrawalManualApproval')
                  }
                "
                allowClear
                placeholder="请选择"
                dictCode="userWithdrawal"
              />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="控制月提现" prop="controlMonthWithdrawal">
              <a-input
                allowClear
                v-model="form.controlMonthWithdrawal"
                @input="
                  () => {
                    $refs.myForm.validateField('controlMonthWithdrawal')
                  }
                "
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="住址" prop="address">
              <a-cascader
                v-model="form.addressCollect"
                :options="addressOptions"
                :load-data="loadAddressOnChange"
                placeholder="请选择"
                @change="onAddressSelected"
              />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="详细地址" prop="detailAddress">
              <a-input allowClear v-model="form.detailAddress" placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="邮编">
              <a-input allowClear v-model="form.postalCode" placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="账户状态" prop="status">
              <j-dict-select-tag
                allowClear
                v-model="form.status"
                @input="
                  () => {
                    $refs.myForm.validateField('status')
                  }
                "
                placeholder="请选择"
                dictCode="status"
              />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-model-item label="代理商状态" prop="agentStatus">
              <j-dict-select-tag
                allowClear
                v-model="form.agentStatus"
                @input="
                  () => {
                    $refs.myForm.validateField('agentStatus')
                  }
                "
                placeholder="请选择"
                dictCode="agentStatus"
              />
            </a-form-model-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="24">
            <a-form-model-item label=" " :colon="false">
              <a-button type="primary" :loading="loading" @click="onSubmit">提交</a-button>
              <a-button @click="closeCurrent()">返回</a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
  </a-card>
</template>

<script>
import CommonApi from '@api/Common'
import { getAction, httpAction } from '@api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { AddressChangeMixin } from '@/mixins/AddressChange'

const Api = {
  queryId: '/sys/user/queryById'
}

export default {
  name: 'DeviceUpdate',
  mixins: [AddressChangeMixin],
  inject: ['closeCurrent'],
  data() {
    return {
      form: {
        id: 0, // 商家id
        provinceCode: undefined, // 省
        cityCode: undefined, // 市
        areaCode: undefined, // 区
        streetCode: undefined, // 镇
        phone: '', // 手机号
        realname: '', // 姓名
        sex: undefined, // 性别
        nickName: undefined, // 昵称
        // 身份证
        wechatRealname: '', // 微信实名
        qqNum: '', // QQ号码
        email: '', // 电子邮件EMAIL
        createTime: '', // 创建日期
        lastLoginTime: undefined, // 最后登录时间
        address: undefined, // 地址
        detailAddress: undefined, // 详细地址
        postalCode: undefined, // 邮编
        status: undefined, // 账户状态
        delFlag: undefined, // 代理商状态,
        addressCollect: []
      },
      loading: false,
      provinceOptions: [],
      cityOptions: [],
      areaOptions: [],
      streetOptions: [],
      networkOptions: [],
      action: '',
      validatorRules: {
        withdrawalFee: [{ required: true, message: '提现手续费不能为空', trigger: 'change' }],
        orderSharding: [{ required: true, message: '订单分成不能为空', trigger: 'change' }],
        passwordPlaintext: [{ required: true, message: '密码明文不能为空', trigger: 'change' }],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'change' },
          {
            validator: this.validatePhone,
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) =>
              validateDuplicateValue('sys_user', 'phone', value, this.form.id, callback),
            trigger: 'blur'
          }
        ],
        agentArea: [
          {
            validator: (rule, value, callback) => {
              if (['provinceCode', 'cityCode', 'areaCode', 'streetCode'].filter(item => this.form[item]).length === 0) {
                callback('区域不能为空')
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        realname: [{ required: true, message: '姓名不能为空', trigger: 'change' }],
        sex: [{ required: true, message: '性別不能为空', trigger: 'change' }],
        nickName: [{ required: true, message: '昵称不能为空', trigger: 'change' }],
        withdrawalMethod: [{ required: true, message: '提现方式不能为空', trigger: 'change' }],
        idCard: [{ required: true, message: '身份证不能为空', trigger: 'change' }],
        reserveSet: [{ required: true, message: '储备金设置不能为空', trigger: 'change' }],
        agentType: [{ required: true, message: '代理商类型不能为空', trigger: 'change' }],
        joinData: [{ required: true, message: '加盟日期不能为空', trigger: 'change' }],
        withdrawalManualApproval: [{ required: true, message: '提现人工审批不能为空', trigger: 'change' }],
        controlMonthWithdrawal: [{ required: true, message: '控制月提现不能为空', trigger: 'change' }],
        address: [{ required: true, message: '住址不能为空', trigger: 'change' }],
        detailAddress: [{ required: true, message: '详细地址不能为空', trigger: 'change' }],
        status: [{ required: true, message: '账户状态不能为空', trigger: 'change' }],
        agentStatus: [{ required: true, message: '代理商状态不能为空', trigger: 'change' }]
      }
    }
  },
  async created() {
    this.action = this.$route.params.id
    this.form.businessId = this.$route.query.id || ''
    this.form.agentType = '1'
    await this.loadAddressForCascader('addressOptions')
    this.getAddress('provinceOptions')
    if (this.action === 'detail' || this.action === 'edit') {
      this.getDetails()
    }
    // 获取地址
  },
  methods: {
    // 获取详情
    getDetails() {
      if (!this.form.businessId) {
        return
      }
      getAction(Api.queryId, { id: this.form.businessId })
        .then(async res => {
          if (res.code === 0) {
            this.form = res.result
            if (this.form.provinceCode) {
              this.getAddress('cityOptions', { provinceCode: this.form.provinceCode })
            }
            if (this.form.cityCode) {
              this.getAddress('areaOptions', { cityCode: this.form.cityCode })
            }
            if (this.form.areaCode) {
              this.getAddress('streetOptions', { areaCode: this.form.areaCode })
            }
            if (this.form.streetCode) {
              this.getAddress('', { streetCode: this.form.streetCode })
            }
            ;['controlMonthWithdrawal', 'reserveSet', 'reserveAmount', 'withdrawnAmount', 'undrawnAmount'].forEach(
              item => (this.form[item] = (this.form[item] || 0) / 100)
            )

            // 住址
            await this.renderAddressAtMounted()
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 获取地址
    getAddress(name, data) {
      getAction(CommonApi.addressList, data).then(res => {
        this[name] = res.result
      })
    },
    // 地址改变
    addressChange(e, name, key, cn) {
      this.$refs.myForm.validateField('agentArea')
      this.form[`${key}Cn`] = cn
      let obj = {}
      // 改变重置后面市区镇
      if (key === 'province') {
        obj = {
          cityCode: undefined,
          cityCn: undefined,
          areaCode: undefined,
          areaCn: undefined,
          streetCode: undefined,
          streetCn: undefined
        }
        this.cityOptions = []
        this.areaOptions = []
        this.streetOptions = []
      } else if (key === 'city') {
        obj = {
          areaCode: undefined,
          areaCn: undefined,
          streetCode: undefined,
          streetCn: undefined
        }
        this.areaOptions = []
        this.streetOptions = []
      } else if (key === 'area') {
        obj = {
          streetCode: undefined,
          streetCn: undefined
        }
        this.streetOptions = []
      }
      this.form = { ...this.form, ...obj }
      if (name && e) {
        this.getAddress(name, { [`${key}Code`]: e })
      }
    },

    // 提交
    onSubmit() {
      this.$refs.myForm.validate(valid => {
        if (valid) {
          const url = `/sys/user/edit`
          this.loading = true
          const data = Object.assign({}, this.form, { username: this.form.phone })
          ;['controlMonthWithdrawal', 'reserveSet', 'reserveAmount', 'withdrawnAmount', 'undrawnAmount'].forEach(
            item => (data[item] = (data[item] || 0) * 100)
          )
          httpAction(url, data, 'put')
            .then(res => {
              if (res.code === 200) {
                this.$message.success(res.message)
                this.closeCurrent()
              } else {
                this.$message.error(res.message)
              }
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    validatePhone(rule, value, callback) {
      const reg1 = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/ // 电话号码
      const reg2 = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/ // 手机号
      if (reg1.test(value) || reg2.test(value)) {
        callback()
      } else {
        callback('请输入正确手机号码')
      }
    }
  }
}
</script>

<style scoped></style>

